<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体内容部分 -->
    <el-card>
      <el-alert
        title="注意:只允许为三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
        class="opt"
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="opt">
        <el-col class="elcolspan"
          ><span>选中商品分类：</span
          ><el-cascader
            v-model="selectKeys"
            :props="cascaderProps"
            :options="parentCateList"
            @change="handleChangeCate"
            clearable
            size="small"
          ></el-cascader
        ></el-col>
      </el-row>
      <!-- tab 标签 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加删除 -->
          <el-button
            type="primary"
            size="small"
            @click="addDialogVisible = true"
            :disabled="isBtnDisabled"
          >
            添加参数
          </el-button>
          <el-table
            :data="manyTableData"
            border
            stripe
            style="width: 100%; margin-top: 15px"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div>
                  <el-tag
                    v-for="(item, i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleClose(i, scope.row)"
                  >
                    {{ item }}
                  </el-tag>
                  <!-- 出发的input 输入框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 触发的按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="索引"
              width="80px"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作" width="160px">
              <template slot-scope="scope">
                <div>
                  <el-button
                    type="primary"
                    size="mini"
                    @click="showEditDialog(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    size="mini"
                    @click="delEditParams(scope.row.attr_id)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="small"
            @click="addDialogVisible = true"
            :disabled="isBtnDisabled"
            >添加属性</el-button
          >
          <el-table
            :data="onlyTableDate"
            border
            stripe
            style="width: 100%; margin-top: 15px"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div>
                  <!-- 循环树池attr_vals的值 -->
                  <el-tag
                    v-for="(item, i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleClose(i, scope.row)"
                  >
                    {{ item }}
                  </el-tag>
                  <!-- 出发的input 输入框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 触发的按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    style="margin-left: 5px"
                    >+ New Tag</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="索引"
              width="80px"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作" width="160px">
              <template slot-scope="scope">
                <div>
                  <el-button
                    type="primary"
                    size="mini"
                    @click="showEditDialog(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    size="mini"
                    @click="delEditParams(scope.row.attr_id)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态、静态属性 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogColse"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText + '名称'" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveParamsForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑属性 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogColse"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText + '名称'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      parentCateList: [],
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selectKeys: [],
      /* 激活tab的状态名称 */
      activeName: "many",
      manyTableData: [],
      onlyTableDate: [],
      addDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
      },
      attrId: "",
      editDialogVisible: false,
      editForm: {
        attr_name: "",
      },
      editFormRules: {
        attr_name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("/categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败！");
      }
      this.parentCateList = res.data;
      console.log(this.parentCateList);
      this.attr;
    },
    async handleChangeCate() {
      const paramsdata = await this.getParamsData();
      this.attrId = this.selectKeys[this.selectKeys.length - 1];
      console.log(this.attrId);
    },

    /* 点击tab出的函数 */
    handleTabClick() {
      console.log(this.activeName);
      this.getParamsData();
    },
    /* 获取params数据 */
    async getParamsData() {
      //console.log(this.selectKeys);
      if (this.selectKeys.length !== 3) {
        this.selectKeys = [];
        this.$message.error("属性只支持到三级分类下");
        this.manyTableData = [];
        this.onlyTableDate = [];
        return;
      }

      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败！");
      }

      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });

      console.log(res.data);

      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableDate = res.data;
      }
    },
    /* 清除校验状态 */
    addDialogColse() {
      this.$refs.addFormRef.resetFields();
    },
    /* 添加参数和属性 */
    saveParamsForm() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.getCateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error(this.titleText + "添加失败！");
        }
        this.$message.success(this.titleText + "添加成功！");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    /* 编辑参数和属性 */
    async showEditDialog(id) {
      this.editDialogVisible = true;
      /* 根据ID查询参数和属性对象 */
      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes/${id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("根据arrtID查询失败！");
      }
      this.editForm = res.data;
      this.attrId = id;
    },
    /* 关闭编辑弹窗 */
    editDialogColse() {
      this.$refs.editFormRef.resetFields();
    },
    /* 编辑保存参数名称 */
    saveEditForm() {
      console.log(this.attrId);
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.getCateId}/attributes/${this.attrId}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("编辑失败！");
        }
        this.$message.success("编辑成功！");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    /* 删除！ */
    async delEditParams(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      if (confirmResult !== "confirm") return this.$message.info("取消删除！");

      const { data: res } = await this.$http.delete(
        `categories/${this.getCateId}/attributes/${attr_id}`
      );

      if (res.meta.status !== 200) {
        return this.$message.error("删除失败！");
      }
      this.$message.success("删除成功！");
      this.getParamsData();
    },
    /* 按下enter键的值 */
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue);
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
    /* 删除参数项目 */
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveAttrVals(row);
    },
    /* 保存参数项 */
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.getCateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("添加失败！");
      }
      this.$message.success("更新成功！");
    },
    /* 点击按钮，展示文本输入框 */
    showInput(row) {
      row.inputVisible = true;
      /* $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码 */
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  },

  /* 计算属性 */
  computed: {
    /* 定义按钮是否为禁用的方法 */
    isBtnDisabled() {
      if (this.selectKeys.length !== 3) {
        return true;
      }
      return false;
    },
    /* 获取商品分类ID */
    getCateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2];
      }
      return null;
    },
    /* 获取动态名称 */
    titleText() {
      if (this.activeName === "many") {
        return "参数";
      } else {
        return "属性";
      }
    },
  },
};
</script>
<style lang="less" scoped>
.opt {
  margin-bottom: 15px;
}
.elcolspan {
  font-size: 14px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
  margin-left: 10px;
}
</style>
